package org.bjf.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * redisson 单机配置
 *
 * @author bjf on 2022/3/4.
 * @version 1.022222
 */
@SpringBootConfiguration
@Slf4j
public class RedissonConfig {
    @Autowired
    private RedisProperties redisProperties;
    @Value("${spring.redis.model:false}")
    private Boolean cluster;

    @Bean
    public RedissonClient redissonClient() throws IOException {
        Config config = new Config();
        config.setCodec(new JsonJacksonCodec());
        //解密redis密码 若配置文件使用的明文密码则不需要
        //String pwd = ConfigTools.decrypt(publicKey, password);
        if (!cluster) {
            String address = redisProperties.getHost() + ":" + redisProperties.getPort();
            address = address.startsWith("redis://") ? address : "redis://" + address;
            SingleServerConfig singleServerConfig = config.useSingleServer();
            singleServerConfig.setAddress(address);
            if (StringUtils.isNotBlank(redisProperties.getPassword())) {
                singleServerConfig.setPassword(redisProperties.getPassword());
            }
            singleServerConfig.setDatabase(redisProperties.getDatabase());
            return Redisson.create(config);
        } else {
            config = Config.fromYAML(new ClassPathResource("redisson.yml").getInputStream());
            config.useClusterServers().setNodeAddresses(redisProperties.getCluster().getNodes());
            if (StringUtils.isNotBlank(redisProperties.getPassword())) {
                config.useClusterServers().setPassword(redisProperties.getPassword());
            }
            return Redisson.create(config);
        }

    }
}
